import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 最大级别的规则，对应的组件，会显示在 App.vue 中
  // 登录
  { path: '/login', component: () => import('@/views/Login.vue') },
  // 注册
  { path: '/reg', component: () => import('@/views/Reg.vue') },
  // 后台主页
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      { path: 'home', component: () => import('@/views/Chart.vue') },
      { path: 'art-list', component: () => import('@/views/article/ArtList.vue') },
      { path: 'art-cate', component: () => import('@/views/article/ArtCate.vue') },
      { path: 'user-info', component: () => import('@/views/user/UserInfo.vue') },
      { path: 'user-pwd', component: () => import('@/views/user/RePwd.vue') },
      { path: 'user-avatar', component: () => import('@/views/user/UserAvatar.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // to.path 表示即将要访问的路由地址
  // next() 直接放行  next(false)  不放行，也不跳转  next('/login) 跳转到指定页面
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    if (store.state.user.token) {
      // 如果有token，直接放行
      next()
    } else {
      // 没有token，跳转到登录页面
      next('/login')
    }
  }
})

export default router
